import { createDiscreteApi } from 'naive-ui'
import {SUCCESS_CODE, TOKEN_NAME, USER_INFO, TOKEN_EXPIRE_CODE} from '~/common/constants'
import {throwError} from '~/utils/throwError'
import {getLangCommonData} from '~/utils/language'
const loadTime = 20 // 秒
function backHomePage() {
  setTimeout(() => {
    navigateTo('/')
  }, 16)
}
export default defineNuxtPlugin((nuxtApp: any) => {
  const naviveDiscApi = () => {
    if (process.client) return createDiscreteApi(['message', 'dialog', 'notification', 'loadingBar'])
    else return null
  }
  const naiveMutual = naviveDiscApi()
  return {
    provide: {
      tokenExpireJudge: (navPage:boolean = true) => {
        // token 判断
        const token = useCookie(TOKEN_NAME)
        const tokenVal = token.value
        let judgeRes = true
        if (!tokenVal) {
          judgeRes = false
          if (process.client) {
            const nuxtApp = useNuxtApp()
            // const warnTokenText = getLangCommonData('tokenExpire')
            nuxtApp.$mutual['notification'].warning({
              content: '令牌不存在或已过期，请重新登录' , // nuxtApp.$i18n.t('common.tokenExpire')
              duration: 4000
            })
            judgeRes = false
          }
          if (navPage) navigateTo('/')
        }
        return judgeRes
      },
      mutual: naiveMutual,
      //   (mType: string) => {
      //   // const { message,dialog,notification,loadingBar} = createDiscreteApi(['message', 'dialog', 'notification', 'loadingBar'])
      //   // dialog.warning({
      //   //   title: '使用渲染函数',
      //   //   content: () => 'Content',
      //   //   action: () => 'Action'
      //   // })
      //   return naiveMutual[mType]
      // },
      request: async (url: string, params: HttpRequest, loadText?: string) => {
        const token = useCookie(TOKEN_NAME)
        const tokenVal = token.value
        let messageLoad = null
        if(process.client) {
          if (localStorage.getItem(USER_INFO) && !tokenVal) {
            // localStorage.clear()
            // token 过期
            const warnTokenText = getLangCommonData('tokenExpire')
            naiveMutual['notification'].warning({
              content: warnTokenText,
              duration: 4000
            })
            backHomePage()
            // useRouter().push({ path: "/" });
            return new Error(warnTokenText)
          }
          messageLoad = naiveMutual['message'].loading(
            loadText || 'Loading',
            { duration: loadTime * 1000 }
          )
        }
        let res = await request(url,params)
        if (process.client && messageLoad) {
          messageLoad.destroy()
        }
        await new Promise(resolve => {
          checkResStatus(resolve, new Date().getTime())
        })
        function checkResStatus (resolve, initTime) {
          setTimeout(() => {
            if (['success', 'error'].includes(res.status.value)) {
              resolve(res)
            } else {
              if ((new Date().getTime() - initTime)/1000 > loadTime) {
                console.log('请求超时--', res)
                resolve()
                throwError('请求超时')
              } else {
                checkResStatus(resolve, initTime)
              }
            }
          })
        }
        if (res.status.value === 'success') {
          const {
            code,
            msg,
            traceId,
            data
          } = res.data.value
          // console.log(code)
          // console.log(msg)
          // console.log(traceId)
          if (code !== SUCCESS_CODE) {
            if (process.client) {
              if (code.startsWith('E')) {
                naiveMutual['notification'].error({
                  content: traceId ? `${msg} - [${traceId}]` : msg,
                  duration: 5000
                })
              } else {
                naiveMutual['notification'].warning({
                  content: msg,
                  duration: 5000
                })
              }
              if (code === TOKEN_EXPIRE_CODE) {
                // useRouter().push({ path: "/" });
                localStorage.removeItem(USER_INFO)
                if (tokenVal) token.value = null // deleteCookie
                backHomePage()
              }
              return new Error(msg)
            } else {
              throwError(msg)
              if (code === TOKEN_EXPIRE_CODE) {
                navigateTo('/')
              }
            }
          } else {
            return {
              msg,
              data,
              code
            }
          }
        } else {
          console.log(res)
          const err = res.error.value
          const errMsg = err.statusCod ? `http code: ${err.statusCode}，${err.data.msg}` : err.message
          if (process.client) {
            naiveMutual['notification'].error({
              content: errMsg,
              duration: 5000
            })
            return new Error(errMsg)
          } else {
            throwError(errMsg)
          }
        }
      }
    }
  }
})
